#include <functional>
#include <utility>
#include <vector>
#include <stdio.h>
#include <unistd.h>
#include <fermat/net/tcp_server.h>
#include <fermat/event/event_loop.h>
#include <fermat/net/socket_address.h>
#include <fermat/common/logging.h>
#include <fermat/common/string.h>
#include <fermat/common/format.h>
#include <fermat/net/socket_stream.h>


size_t sendcount = 0;
class EchoServer {
public:
    EchoServer(fermat::event::EventLoopPtr loop, fermat::net::SocketAddress& listenAddr)
        :_loop(loop),
         _server(loop, listenAddr, "EchoServer")
    {
        _server.setConnectionCallback(
                    std::bind(&EchoServer::onConnection, this, std::placeholders::_1));
        _server.setMessageCallback(
                    std::bind(&EchoServer::onMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    void start()
    {
        _server.setThreadNum(1);
        _server.start();
  }
  // void stop();

 private:
  void onConnection(const fermat::net::TcpConnectionPtr& conn)
  {
    LOG_INFO("new connection");
      (void)conn;
   // conn->send("hello\n");
  }

  void onMessage(const fermat::net::TcpConnectionPtr& conn, fermat::PageBufferSliceQueuePtr buf, fermat::Timestamp time)
  {
    fermat::net::SocketStream<0> stream(buf);
    sendcount += stream.size();
    LOG_INFO ("{} recv {} bytes at {}", conn->name(), stream.size(), time.epochTime());
    buf->clear();
    /*if (msg == "exit\n")
    {
      conn->send("bye\n");
      conn->shutdown();
    }
    if (msg == "quit\n")
    {
      loop_->quit();
    }
    */
    //conn->send(msg);
	
  }

  fermat::event::EventLoopPtr  _loop;
  fermat::net::TcpServer       _server;
};
void printcount()
{
	fermat::print("{}", sendcount);
}



int main(int argc, char* argv[])
{
  LOG_SET_LEVEL(fermat::log::ll_info);
  LOG_INFO("pid = {} , tid = {}", getpid(), fermat::this_thread::tid());

  fermat::event::EventLoopPtr  loop(new fermat::event::EventLoop());
  fermat::net::SocketAddress listenAddr;
  listenAddr.set("0.0.0.0", "2000");
  EchoServer server(loop, listenAddr);
  server.start();
  loop->runEvery(3*1000*1000,printcount);
  loop->loop();
  return 0; 
}